package com.shoux.api.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.shoux.api.enm.MsgEnum;
import com.shoux.api.exception.BeanUtilsException;
import com.shoux.api.tools.MsgUtils;
import com.shoux.api.tools.StringUtils;
import com.shoux.api.web.dao.apiData.CompanyDataMapper;
import com.shoux.api.web.dao.apiData.CompanyDataTargetMapper;
import com.shoux.api.web.dao.apiData.WxPrecreditresultL1Mapper;
import com.shoux.api.web.dao.windSx.CompanyInfoMapper;
import com.shoux.api.web.dao.windSx.DicFieldValuesMapper;
import com.shoux.api.web.entity.CompanyInfoEntity;
import com.shoux.api.web.entity.MsgEntity;
import com.shoux.api.web.entity.QuestionnaireInfoEntity;
import com.shoux.api.web.dao.windSx.QuestionnaireInfoMapper;
import com.shoux.api.web.entity.ScopeEntity;
import com.shoux.api.web.entity.apiData.WxPrecreditresultL1Entity;
import com.shoux.api.web.entity.query.CommonQuery;
import com.shoux.api.web.entity.query.CommonResponse;
import com.shoux.api.web.service.QuestionnaireInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 问卷信息表 服务实现类
 * </p>
 *
 * @author chris
 * @since 2022-03-17
 */
@Slf4j
@Service
public class QuestionnaireInfoServiceImpl extends ServiceImpl<QuestionnaireInfoMapper, QuestionnaireInfoEntity> implements QuestionnaireInfoService {

    @Autowired
    private CompanyInfoMapper companyInfoMapper;
    @Resource
    private WxPrecreditresultL1Mapper wxPrecreditresultL1Mapper;

    @Autowired
    private QuestionnaireInfoMapper questionnaireInfoMapper;

    @Override
    public MsgEntity submitQuestnrInfo(CommonQuery commonQuery) {
        int submitSum = 0;
        if (checkBaseInfo(commonQuery)) {
            try {
                // 判断该企业基本信息是不是已经存在，存在的话，逻辑删除，然后再插入新的
                LambdaQueryWrapper<CompanyInfoEntity> queryWrapper = Wrappers.lambdaQuery(CompanyInfoEntity.class)
                        .like(StringUtils.isNotBlank(commonQuery.getShtyxydm()), CompanyInfoEntity::getShtyxydm, commonQuery.getShtyxydm());
                List<CompanyInfoEntity> companyInfoList = companyInfoMapper.selectList(queryWrapper);
                if (!CollectionUtils.isEmpty(companyInfoList)) {
                    List<Long> ids = companyInfoList.stream().map(o -> o.getId()).collect(Collectors.toList());
                    companyInfoMapper.deleteBatchIds(ids);
                }

                CompanyInfoEntity companyInfoEntity = new CompanyInfoEntity();
                BeanUtils.copyProperties(commonQuery, companyInfoEntity);
                submitSum += companyInfoMapper.insert(companyInfoEntity);

                // 判断该企业问卷信息是不是已经存在，存在的话，逻辑删除，然后再插入新的
                LambdaQueryWrapper<QuestionnaireInfoEntity> quesQueryWrapper = Wrappers.lambdaQuery(QuestionnaireInfoEntity.class)
                        .like(StringUtils.isNotBlank(commonQuery.getShtyxydm()), QuestionnaireInfoEntity::getQyshxydm, commonQuery.getShtyxydm());
                List<QuestionnaireInfoEntity> questionInfoList = questionnaireInfoMapper.selectList(quesQueryWrapper);
                if (!CollectionUtils.isEmpty(questionInfoList)) {
                    List<Long> ids = questionInfoList.stream().map(o -> o.getId()).collect(Collectors.toList());
                    questionnaireInfoMapper.deleteBatchIds(ids);
                }
                QuestionnaireInfoEntity questionnaireInfoEntity = new QuestionnaireInfoEntity();
                BeanUtils.copyProperties(commonQuery, questionnaireInfoEntity);
                questionnaireInfoEntity.setQyshxydm(commonQuery.getShtyxydm());
                submitSum += questionnaireInfoMapper.insert(questionnaireInfoEntity);
            } catch (Exception e) {
                e.printStackTrace();
                throw new BeanUtilsException(e.getMessage());
            }
        }

        if (submitSum != 2) {
            throw new BeanUtilsException("企业信息提交失败");
        }

        // 获取预授信信息
//        CommonResponse commonResponse = getQysx(commonQuery);
//        return MsgUtils.successWhithData(commonResponse);
//
//        CommonResponse commonResponse = getQysx(commonQuery);
        // 获取预授信信息
        return getQysx(commonQuery);
    }

    // 校验企业信息
    private boolean checkBaseInfo(CommonQuery commonQuery) {
        boolean checkResult = true;
        // 校验企业基本信息
        if (StringUtils.isEmpty(commonQuery.getQymc()) ||
//                StringUtils.isEmpty(commonQuery.getFddbr()) ||
                commonQuery.getAge() == null ||
//                StringUtils.isEmpty(commonQuery.getSfzjhm()) ||
                StringUtils.isEmpty(commonQuery.getShtyxydm())) {
            throw new BeanUtilsException("请输入以下企业基本信息: 企业社会信用代码/企业名称/法人年龄");
        }

        // 提交问卷信息的时候 校验问卷信息有无漏填
        if (commonQuery.getDkyt() == null
                || commonQuery.getQnljlrze() == null
                || commonQuery.getQnxssr() == null
                || commonQuery.getQnnsze() == null
                || commonQuery.getQnzcze() == null
                || commonQuery.getQydkyefaj() == null
                || commonQuery.getWloyhkzeaj() == null) {
            throw new BeanUtilsException("请填写所有问卷信息");
//            throw new BeanUtilsException("请输入以下问卷信息: 贷款用途");
        }

        return checkResult;
    }

    @Resource
    private CompanyDataTargetMapper companyDataTargetMapper;
    @Autowired
    private DicFieldValuesMapper dicFieldValuesMapper;
    @Resource
    private CompanyDataMapper companyDataMapper;

    // 获取企业预授信额度信息
    private MsgEntity getQysx(CommonQuery commonQuery) {

        CommonResponse commonResponse = new CommonResponse();
        MsgEntity msgEntity = new MsgEntity();
        try {
            boolean flag = true;
            int countNum = companyDataMapper.getConutByMc(StringUtils.replaceAllTo(commonQuery.getQymc()));
            if (countNum > 0) {
                //法定代表人年龄评分
                Double ageRatio = companyInfoMapper.getAgeRatio(commonQuery.getAge());
                log.info("法定代表人年龄评分:" + ageRatio);
                WxPrecreditresultL1Entity wxPrecreditresultL1 = wxPrecreditresultL1Mapper.getOneByCompanyName(StringUtils.replaceAllTo(commonQuery.getQymc()));
                System.out.println(wxPrecreditresultL1);
                if (wxPrecreditresultL1 != null && "1".equals(wxPrecreditresultL1.getIsallow())) {
                    //企业综合评分(缺法人年龄评分)
                    Double scorecard = wxPrecreditresultL1.getScorecard();
                    log.info("企业综合评分(缺法人年龄评分):" + scorecard);
                    if (scorecard != null) {
                        int min = 0;
                        int max = 0;
                        //最终评分
                        double score = scorecard;
                        score += (ageRatio != null ? ageRatio : 0);
                        log.info("最终评分:" + score);
                        //评级系数
                        Double scoreRatio = companyInfoMapper.getScoreRatio(score);
                        log.info("评级系数:" + scoreRatio);
                        if (scoreRatio != null) {
                            //行业门类名称
                            String hylbMc = companyDataTargetMapper.getHylbMcBY(commonQuery.getShtyxydm());
                            //行业调整系数
                            Double hylbRatio = companyInfoMapper.getHylbRatio(StringUtils.isEmpty(hylbMc) ? "空值" : hylbMc.trim());
                            log.info(hylbMc + "行业门类;行业调整系数:" + hylbRatio);
                            String qnxssr = dicFieldValuesMapper.getValueBy(commonQuery.getQnxssr(), "去年销售收入");
                            String qnzcze = dicFieldValuesMapper.getValueBy(commonQuery.getQnzcze(), "去年资产总额");
                            String qnljlrze = dicFieldValuesMapper.getValueBy(commonQuery.getQnljlrze(), "去年累计利润总额");
                            String dkyt = dicFieldValuesMapper.getValueBy(commonQuery.getDkyt(), "贷款用途");
                            //贷款用途系数
                            Double dkytRatio = companyInfoMapper.getDkytRatio(dkyt);
                            String qydkyefaj = dicFieldValuesMapper.getValueBy(commonQuery.getQydkyefaj(), "企业贷款余额(非按揭)");
                            String wloyhkzeaj = dicFieldValuesMapper.getValueBy(commonQuery.getWloyhkzeaj(), "未来24个月企业还款总额(按揭)");
                            //根据销售收入测算	企业上一年销售收入 * 行业调整系数*评级系数
                            final ScopeEntity scopeEntity = ScopeEntity.strTo(qnxssr);
                            //根据公司资产测算	企业上一年资产总额  * 行业调整系数*评级系数
                            final ScopeEntity scopeEntity1 = ScopeEntity.strTo(qnzcze);
                            //根据企业利润测算	企业上一年利润 * 评级系数 * 行业调整系数
                            final ScopeEntity scopeEntity2 = ScopeEntity.strTo(qnljlrze);

                            final ScopeEntity scopeEntity3 = ScopeEntity.strTo(qydkyefaj);

                            final ScopeEntity scopeEntity4 = ScopeEntity.strTo(wloyhkzeaj);
                            double creditrange = wxPrecreditresultL1.getCreditrange() * scoreRatio;
                            if (scopeEntity.getMaxValue() != null && scopeEntity1.getMaxValue() != null && scopeEntity2.getMaxValue() != null) {
                                double qnxssrD = scopeEntity.getMaxValue() * hylbRatio * scoreRatio;
                                double qnzczeD = scopeEntity1.getMaxValue() * hylbRatio * scoreRatio;
                                double qnljlrzeD = scopeEntity2.getMaxValue() * hylbRatio * scoreRatio;
                                log.info("最大值；预授信额：" + creditrange + "，销售收入：" + qnxssrD + "，资产：" + qnzczeD + "，利润：" + qnljlrzeD + "，贷款用途：" + dkytRatio + "，贷款余额：" + scopeEntity3.getMinValue() + "，还款余额：" + scopeEntity4.getMinValue());
                                max = (int) ((((creditrange + qnxssrD + qnzczeD + qnljlrzeD) / 5) * dkytRatio) - (scopeEntity3.getMinValue() + scopeEntity4.getMinValue()));
                            }

                            if (scopeEntity.getMinValue() != null && scopeEntity1.getMinValue() != null && scopeEntity2.getMinValue() != null) {

                                double qnxssrD = scopeEntity.getMinValue() * hylbRatio * scoreRatio;
                                double qnzczeD = scopeEntity1.getMinValue() * hylbRatio * scoreRatio;
                                double qnljlrzeD = scopeEntity2.getMinValue() * hylbRatio * scoreRatio;
                                log.info("最小值；预授信额：" + creditrange + "，销售收入：" + qnxssrD + "，资产：" + qnzczeD + "，利润：" + qnljlrzeD + "，贷款用途：" + dkytRatio + "，贷款余额：" + scopeEntity3.getMaxValue() + "，还款余额：" + scopeEntity4.getMaxValue());
                                min = (int) ((((creditrange + qnxssrD + qnzczeD + qnljlrzeD) / 5) * dkytRatio) - (scopeEntity3.getMaxValue() + scopeEntity4.getMaxValue()));
                            }
                            if (min < 5) {
                                min = 0;
                                max = 0;
                            }

                            if (max > 300) {
                                max = 300;
                            }
                            if (min > 300) {
                                min = 300;
                            }
                            if (min == max) {
                                min = max;
                            } else if (min > max) {
                                max = min;
                            }
                            commonResponse.setSxyged(min + "-" + max); //ToDO
                            wxPrecreditresultL1.setCreaditRangeFinal(commonResponse.getSxyged());
                            wxPrecreditresultL1.setCreaditRangeFinalTime(LocalDateTime.now());
                            wxPrecreditresultL1Mapper.updateById(wxPrecreditresultL1);
                            msgEntity.setCode(MsgEnum.SIMPLESUCCESS.getCode());
                            msgEntity.setMsg(MsgEnum.SIMPLESUCCESS.getDesc());
                            flag = false;
                        } else {
                            msgEntity.setMsg("未查询到评级系数，请联系对应管理人员!");
                        }
                    } else {
                        msgEntity.setMsg("未查询到评分，请联系对应管理人员!");
                    }
                } else {
                    msgEntity.setMsg("很抱歉，您的企业暂不符合要求!");
                }
            } else {
                msgEntity.setMsg("很抱歉，您的企业不在本次授信名单中!");
            }
            if (flag) {
                msgEntity.setCode(MsgEnum.SIMPLEFAIL.getCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
            msgEntity.setCode(MsgEnum.SIMPLEFAIL.getCode());
            msgEntity.setMsg("额度计算异常，请联系管理员！");
        }
        log.info("授信额度：" + commonResponse.getSxyged());
        BeanUtils.copyProperties(commonQuery, commonResponse);
        msgEntity.setData(commonResponse);
        return msgEntity;
    }


}
